//
//  ApplyRefundVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/3/18.
//  Copyright © 2020 cat. All rights reserved.
//

#import "ApplyRefundVC.h"
#import "TZImagePickerController.h"
#import <Qiniu/QiniuSDK.h>

@interface ApplyRefundVC ()<UIPickerViewDelegate,UIPickerViewDataSource,UITextViewDelegate,TZImagePickerControllerDelegate>{
    UIScrollView *_backScroll;
    
    UIButton *returnGoodsBtn;
    UIButton *refundBtn;
    UIButton *imageBtn;
    UITextField *reasonField;
    
    UILabel *priceLb;
    UILabel *wordCountLb;

    MyTextView *contentText;
    
    NSArray *reasonArr;
    
    UIView *reasonPickBack;
    UIPickerView *reasonPicker;
    NSString *selReasonStr;
    NSString *selReasonID;

    NSInteger selRow;

    NSString *refundtype;
    NSMutableArray *imageArray;

    UIButton *delBtn;
    NSString *picThumbsStr;
}
@property (nonatomic, strong)UIImageView *orderImg;
@property (nonatomic, strong)UILabel *orderTitleLb;
@property (nonatomic, strong)UILabel *orderContentLb;
@property (nonatomic, strong)UILabel *orderPriceLb;
@property (nonatomic, strong)UILabel *orderCountLb;

@end

@implementation ApplyRefundVC


-(void)requestReason{
    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.getRefundReason"];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          };
    [WYNetworking postWithUrl:@"Buyer.getRefundReason" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            reasonArr = info;
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = YZMsg(@"退款申请");
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    reasonArr = [NSArray array];
    imageArray = [NSMutableArray array];
    selReasonID = @"";
    refundtype = @"0";
    picThumbsStr = @"";

    
    _backScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight-40)];
    _backScroll.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:_backScroll];
    [self createUI];
    
    UIButton *submitBtn = [UIButton buttonWithType:0];
    submitBtn.frame = CGRectMake(0, _window_height-40-ShowDiff, _window_width, 40);
    [submitBtn setTitle:YZMsg(@"提交申请") forState:0];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:0];
    submitBtn.titleLabel.font =[UIFont systemFontOfSize:14];
    [submitBtn setBackgroundColor:Pink_Cor];
    [submitBtn addTarget:self action:@selector(submitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitBtn];
    
    [self requestReason];
}
-(void)createUI{
    _orderImg = [[UIImageView alloc]init];
    _orderImg.frame = CGRectMake(15, 15, 90, 90);
    _orderImg.backgroundColor = [UIColor lightGrayColor];
    _orderImg.layer.cornerRadius = 5;
    _orderImg.layer.masksToBounds = YES;
    _orderImg.contentMode = UIViewContentModeScaleAspectFill;
    [_orderImg sd_setImageWithURL:[NSURL URLWithString:self.models.orderspec_thumb_format]];
    [_backScroll addSubview:_orderImg];
    
    _orderTitleLb = [[UILabel alloc]init];
    _orderTitleLb.textColor = [UIColor blackColor];
    _orderTitleLb.font = [UIFont systemFontOfSize:14];
    _orderTitleLb.text = self.models.order_goods_name;
    [_backScroll addSubview:_orderTitleLb];
    [_orderTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_orderImg.mas_right).offset(5);
        make.top.equalTo(_orderImg).offset(8);
        make.height.mas_equalTo(18);
    }];
    
    _orderPriceLb = [[UILabel alloc]init];
    _orderPriceLb.textColor = [UIColor blackColor];
    _orderPriceLb.font = [UIFont systemFontOfSize:14];
    _orderPriceLb.text = self.models.order_price;
    _orderPriceLb.textAlignment = NSTextAlignmentRight;
    [_backScroll addSubview:_orderPriceLb];
    [_orderPriceLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
        make.centerY.height.equalTo(_orderTitleLb);
    }];
    _orderContentLb = [[UILabel alloc]init];
    _orderContentLb.textColor = Normal_TextColor;
    _orderContentLb.font = [UIFont systemFontOfSize:14];
    _orderContentLb.text =self.models.order_spec_name;// @"麻辣鲜香味";
    [_backScroll addSubview:_orderContentLb];
    [_orderContentLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_orderTitleLb);
        make.top.equalTo(_orderTitleLb.mas_bottom).offset(5);
        make.height.equalTo(_orderTitleLb);
    }];
    
    _orderCountLb = [[UILabel alloc]init];
    _orderCountLb.textColor = Normal_TextColor;
    _orderCountLb.font = [UIFont systemFontOfSize:14];
    _orderCountLb.text =[NSString stringWithFormat:@"x%@",self.models.order_nums];
    _orderCountLb.textAlignment = NSTextAlignmentRight;
    [_backScroll addSubview:_orderCountLb];
    [_orderCountLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
        make.centerY.height.equalTo(_orderContentLb);
    }];

    [PublicObj lineViewWithFrame:CGRectMake(0, _orderImg.bottom+5, _window_width, 5) andColor:RGB(245, 245, 245) andView:_backScroll];

    NSArray *arr = @[YZMsg(@"退款方式"),YZMsg(@"退款原因"),YZMsg(@"退款金额")];
    for (int i = 0; i < arr.count; i ++) {
        UILabel *titleLb = [[UILabel alloc]init];
        titleLb.frame = CGRectMake(15, _orderImg.bottom+10 + i*40, 80, 40);
        titleLb.font = [UIFont systemFontOfSize:14];
        titleLb.textColor = Normal_TextColor;
        titleLb.text = arr[i];
        [_backScroll addSubview:titleLb];
        
        if (i == 0) {
            //['status']  订单状态  -1 已关闭  0 待付款 1 待发货 2 待收货 3 待评价 4 已评价 5 退款
            refundBtn = [UIButton buttonWithType:0];
            refundBtn.frame = CGRectMake(titleLb.right+10, _orderImg.bottom+10 + i*40, 80+15, 40);
            [refundBtn setTitleColor:Normal_TextColor forState:0];
            [refundBtn setTitleColor:Pink_Cor forState:UIControlStateSelected];
            [refundBtn setTitle:YZMsg(@"仅退款") forState:0];
            refundBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            [refundBtn setImage:[UIImage imageNamed:@"refund_未选"] forState:UIControlStateNormal];
            [refundBtn setImage:[UIImage imageNamed:@"refund_已选"] forState:UIControlStateSelected];
            refundBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
            refundBtn.tag = 20000;
            [refundBtn addTarget:self action:@selector(refundTypeClick:) forControlEvents:UIControlEventTouchUpInside];
            [_backScroll addSubview:refundBtn];
            refundBtn.selected = YES;

            if ([self.models.order_status isEqual:@"2"] ||[self.models.order_status isEqual:@"3"]) {
                returnGoodsBtn = [UIButton buttonWithType:0];
                returnGoodsBtn.frame = CGRectMake(refundBtn.right+20, _orderImg.bottom+10 + i*40, 80, 40);
                if ([lagType isEqual:EN]) {
                    returnGoodsBtn.frame = CGRectMake(refundBtn.right+20, _orderImg.bottom+10 + i*40, 80+35, 40);
                }
                [returnGoodsBtn setTitleColor:Normal_TextColor forState:0];
                [returnGoodsBtn setTitleColor:Pink_Cor forState:UIControlStateSelected];
                [returnGoodsBtn setTitle:YZMsg(@"退货退款") forState:0];
                returnGoodsBtn.titleLabel.font = [UIFont systemFontOfSize:14];
                [returnGoodsBtn setImage:[UIImage imageNamed:@"refund_未选"] forState:UIControlStateNormal];
                [returnGoodsBtn setImage:[UIImage imageNamed:@"refund_已选"] forState:UIControlStateSelected];
                returnGoodsBtn.tag = 20001;
                returnGoodsBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
                [returnGoodsBtn addTarget:self action:@selector(refundTypeClick:) forControlEvents:UIControlEventTouchUpInside];

                [_backScroll addSubview:returnGoodsBtn];
                returnGoodsBtn.selected = NO;

            }
        }else if (i == 1){
            reasonField = [[UITextField alloc]init];
            reasonField.frame  = CGRectMake(titleLb.right+10, _orderImg.bottom+10 + i*40, 200, 40);
//            reasonField.placeholder = YZMsg(@"请选择");
            reasonField.font = [UIFont systemFontOfSize:14];
            reasonField.userInteractionEnabled = NO;
            reasonField.textColor = Normal_TextColor;
            NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:YZMsg(@"请选择") attributes:@{NSForegroundColorAttributeName:Normal_TextColor,
                         NSFontAttributeName:reasonField.font
                 }];
            reasonField.attributedPlaceholder = attrString;
            [_backScroll addSubview:reasonField];
            
            UIImageView *rightImg = [[UIImageView alloc]init];
            rightImg.frame = CGRectMake(_window_width-40, _orderImg.bottom+20 + i*40, 20, 20);
            rightImg.image = [UIImage imageNamed:@"shop_right"];
            [_backScroll addSubview:rightImg];

            UIButton *select = [UIButton buttonWithType:0];
            select.frame = CGRectMake(titleLb.right+10, _orderImg.bottom+10 + i*40, _window_width, 40);
            [select addTarget:self action:@selector(selectReason) forControlEvents:UIControlEventTouchUpInside];
            [_backScroll addSubview:select];

        }else{
            priceLb = [[UILabel alloc]init];
            priceLb.frame = CGRectMake(titleLb.right+10, _orderImg.bottom+10 + i*40, 200, 40);
            priceLb.font = [UIFont systemFontOfSize:14];
            priceLb.textColor = Pink_Cor;
            priceLb.text = self.models.order_total;
            [_backScroll addSubview:priceLb];
        }
    }
    
    UILabel *line = [[UILabel alloc]init];
    line.frame = CGRectMake(0, priceLb.bottom+5, _window_width, 5);
    line.backgroundColor = RGB(245, 245, 245);
    [_backScroll addSubview:line];
    
    contentText = [[MyTextView alloc]init];
    contentText.frame = CGRectMake(10, line.bottom+5, _window_width-20, 150);
    contentText.placeholderColor = Normal_TextColor;
    contentText.placeholder =YZMsg(@"请填写10个字以上的问题描述以便我们提供更好的帮助");
    contentText.font = [UIFont systemFontOfSize:14];
    contentText.delegate = self;
    contentText.backgroundColor = RGB(245, 245, 245);
    contentText.textColor = [UIColor blackColor];
    [_backScroll addSubview:contentText];
    
// --原来有上传图片功能，现在去掉了
    imageBtn = [UIButton buttonWithType:0];
    imageBtn.frame = CGRectMake(15, _backScroll.height-80, 70, 70);
    [imageBtn setBackgroundImage:[UIImage imageNamed:getImagename(@"refund_upimg")] forState:0];
    [imageBtn addTarget:self action:@selector(uploadImage) forControlEvents:UIControlEventTouchUpInside];
//    [_backScroll addSubview:imageBtn];

    delBtn = [UIButton buttonWithType:0];
    delBtn.frame = CGRectMake(imageBtn.width-25, 5, 20, 20);
    [delBtn setBackgroundImage:[UIImage imageNamed:@"comm_del"] forState:0];
    [delBtn addTarget:self action:@selector(delVideoClick) forControlEvents:UIControlEventTouchUpInside];
//    [imageBtn addSubview:delBtn];
    delBtn.hidden = YES;

    wordCountLb = [[UILabel alloc]init];
    wordCountLb.frame = CGRectMake(_window_width-100, contentText.bottom+10, 90, 20);
//    wordCountLb.centerY = imageBtn.centerY;
    wordCountLb.font = [UIFont systemFontOfSize:14];
    wordCountLb.textColor = Normal_TextColor;
    wordCountLb.text = @"0/300";
    wordCountLb.textAlignment = NSTextAlignmentRight;
    [_backScroll addSubview:wordCountLb];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
-(void)refundTypeClick:(UIButton *)sender{
    if (sender.tag == 20000) {
        refundBtn.selected = YES;
        returnGoodsBtn.selected = NO;
        refundtype = @"0";
    }else{
        refundBtn.selected = NO;
        returnGoodsBtn.selected = YES;
        refundtype = @"1";
    }
}
//选择图片
-(void)uploadImage{
    TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1-imageArray.count delegate:self];
    imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
    imagePC.modalPresentationStyle = 0;
    imagePC.showSelectBtn = YES;
    imagePC.allowCrop = NO;
    imagePC.allowPickingOriginalPhoto = NO;
    imagePC.oKButtonTitleColorNormal = Pink_Cor;
    imagePC.allowTakePicture = YES;
    imagePC.allowTakeVideo = NO;
    imagePC.allowPickingVideo = NO;
    imagePC.allowPickingMultipleVideo = NO;
    [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
}
-(void)delVideoClick{
    delBtn.hidden = YES;
    [imageArray removeAllObjects];
    [imageBtn setBackgroundImage:[UIImage imageNamed:getImagename(@"refund_upimg")] forState:0];
}
#pragma mark------选择原因-------
-(void)selectReason{
    [self.view endEditing:YES];
    if (!reasonPickBack) {
        reasonPickBack = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        reasonPickBack.backgroundColor = RGB_COLOR(@"#000000", 0.3);
        [self.view addSubview:reasonPickBack];
        
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-240, _window_width, 40)];
        titleView.backgroundColor = [UIColor whiteColor];
        [reasonPickBack addSubview:titleView];
        
        [PublicObj lineViewWithFrame:CGRectMake(0, titleView.height-1, _window_width, 1) andColor:RGB(250, 250, 250) andView:titleView];
        
        UIButton *cancleBtn = [UIButton buttonWithType:0];
        cancleBtn.frame = CGRectMake(10, 0, 80, 40);
        cancleBtn.tag = 100;
        [cancleBtn setTitle:YZMsg(@"取消") forState:0];
        [cancleBtn setTitleColor:[UIColor blackColor] forState:0];
        cancleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [cancleBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:cancleBtn];
        
        UIButton *sureBtn = [UIButton buttonWithType:0];
        sureBtn.frame = CGRectMake(_window_width-90, 0, 80, 40);
        sureBtn.tag = 101;
        [sureBtn setTitle:YZMsg(@"完成") forState:0];
        [sureBtn setTitleColor:[UIColor blackColor] forState:0];
        sureBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [sureBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:sureBtn];
        
        UILabel *titlelb = [[UILabel alloc]init];
        titlelb.frame = CGRectMake(_window_width/2-40, 0, 80, 40);
        titlelb.font = [UIFont systemFontOfSize:15];
        titlelb.text = YZMsg(@"退款原因");
        titlelb.textColor = [UIColor blackColor];
        [titleView addSubview:titlelb];
        
        reasonPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, _window_height-200, _window_width, 200)];
        reasonPicker.backgroundColor = [UIColor whiteColor];
        reasonPicker.delegate = self;
        reasonPicker.dataSource = self;
        reasonPicker.showsSelectionIndicator = YES;
        [reasonPicker selectRow: 0 inComponent: 0 animated: YES];
        [reasonPickBack addSubview:reasonPicker];
    }else{
        reasonPickBack.hidden = NO;
    }

}
- (void)cityCancleOrSure:(UIButton *)button{
    if (button.tag == 100) {
        //return;
    }else{
        reasonField.text =  selReasonStr;
    }
    reasonPickBack.hidden = YES;
    
}
#pragma mark--- Picker Data Source Methods-----
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return reasonArr.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [reasonArr[row] valueForKey:@"name"];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    selReasonStr = [reasonArr[row] valueForKey:@"name"];
    selReasonID =minstr([reasonArr[row] valueForKey:@"id"]) ;
    selRow = row;
    [reasonPicker reloadAllComponents];
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        pickerLabel.font = [UIFont systemFontOfSize:15];
    }
    if (row == selRow) {
        pickerLabel.textColor = Pink_Cor;
        selReasonStr =[reasonArr[selRow] valueForKey:@"name"];
        selReasonID =[reasonArr[row] valueForKey:@"id"];

    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;

}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    NSLog(@"------多选择图片--：%@",photos);
    [imageArray addObjectsFromArray:photos];
    [imageBtn setBackgroundImage:photos[0] forState:0];
    delBtn.hidden = NO;

}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView*)textView {

    NSString *toBeString = textView.text;
    NSString *lang = [[[UITextInputMode activeInputModes]firstObject] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textView markedTextRange];//获取高亮部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        //没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 300) {
                textView.text = [toBeString substringToIndex:300];
                wordCountLb.text = [NSString stringWithFormat:@"%lu/300",textView.text.length];
            }else{
                wordCountLb.text = [NSString stringWithFormat:@"%lu/300",toBeString.length];
            }
        }else{
            //有高亮选择的字符串，则暂不对文字进行统计和限制
        }
    }else{
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > 300) {
            textView.text = [toBeString substringToIndex:300];
            wordCountLb.text = [NSString stringWithFormat:@"%lu/300",textView.text.length];
        }else{
            wordCountLb.text = [NSString stringWithFormat:@"%lu/300",toBeString.length];
        }
    }
    
}
#pragma mark------提交----------
-(void)submitBtnClick{
    [self uploadService];
}
-(void)uploadService{

    if (selReasonID.length < 1) {
        [MBProgressHUD showError:YZMsg(@"请选择退款原因")];
        return;
    }
    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.applyRefundGoodsOrder"];
    
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.models.order_id, @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":self.models.order_id,
                          @"reasonid":selReasonID,
                          @"content":contentText.text,
                          @"type":refundtype,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    
    [WYNetworking postWithUrl:@"Buyer.applyRefundGoodsOrder" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:msg];
            [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}
@end
